// static/js/register.js
import { setupPasswordToggle } from './common.js';
import { userManager } from './auth.js';
// 验证码不能点击切换的问题解决：设为全局函数
window.reloadCaptcha = function() {
    const captchaImage = document.getElementById("captcha-img");
    captchaImage.src = "/captcha?ts=" + Date.now();
};
document.getElementById('register-email').addEventListener('blur', function(event) {
    console.log("进入验证邮箱是否被注册过的函数")
    const emailInput = event.target;
    const email = emailInput.value.trim();

    // 基础验证：非空且符合邮箱格式
    if (!email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
        return; // 不处理无效邮箱格式
    }

    // 发送验证请求
    fetch('/verify_user_mail_has_been_registered', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ user_mail: email })
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        return response.json();
    })
    .then(data => {
        if (data.success) {
            console.log('邮箱可用');
        } else {
            emailInput.value = ''; // 清除输入
            alert('该邮箱已被注册');
        }
    })
    .catch(error => {
        console.error('验证失败:', error);
    });
});

document.addEventListener('DOMContentLoaded', () => {
    // 设置密码切换
    setupPasswordToggle();

    // 注册表单处理
    document.getElementById('registerForm').addEventListener('submit', async (e) => {
        e.preventDefault();
        // 重置错误状态
        resetValidationErrors();

        // 获取输入的用户信息
        const username = document.getElementById('user_name').value.trim(); // 新增用户名获取
        const email = document.getElementById('register-email').value.trim();
        const password = document.getElementById('register-password').value;
        const confirmPassword = document.getElementById('confirm-password').value;
        const captcha = document.getElementById('captcha').value.trim(); // 修改为正确的ID
        const mail_captcha = document.getElementById('mail_captcha').value.trim();
        // 验证输入
        let isValid = true;

        // 验证用户名
        if (!username) {
            showValidationError('user_name', '请输入用户名');
            isValid = false;
        }

        // 验证邮箱
        if (!validateEmail(email)) {
            showValidationError('register-email', '请输入有效的邮箱地址');
            isValid = false;
        }

        // 验证密码
        const passwordError = validatePassword(password);
        if (passwordError) {
            showValidationError('register-password', passwordError);
            isValid = false;
        }

        // 验证密码一致性
        if (password !== confirmPassword) {
            showValidationError('confirm-password', '两次输入的密码不一致');
            isValid = false;
        }

        // 验证验证码是否输入
        if (!captcha) {
            showValidationError('captcha', '请输入验证码');
            isValid = false;
        }

        // 如果验证失败，停止提交
        if (!isValid) {
            return;
        }
        
        // 添加加载状态
        const submitBtn = document.querySelector('.login-button');
        submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 注册中';
        submitBtn.disabled = true;

        try {
            // 发送注册请求到指定路由
            const response = await fetch('/register_process', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    user_name: username,
                    user_mail: email,
                    user_password: password,
                    captcha: captcha,
                    mail_captcha: mail_captcha
                })
            });

            const result = await response.json();

            if (result.success) {
                // 注册成功提示并跳转
                // 注册成功提示并跳转到登录页面
                window.location.href = '/login';
                setTimeout(() => {
                    window.location.href = '/login';
                }, 1500);
            } else {
                // 显示错误信息
                if (result.field && result.message) {
                    showValidationError(result.field, result.message);
                } else {
                    alert('注册失败：' + (result.message || '未知错误'));
                }
                // 恢复提交按钮
                submitBtn.innerHTML = '注册';
                submitBtn.disabled = false;
            }
        } catch (error) {
            // 错误处理
            alert('注册请求异常：' + error.message);
            // 恢复提交按钮
            submitBtn.innerHTML = '注册';
            submitBtn.disabled = false;
        }
    });
    // 添加获取验证码按钮点击事件
    document.getElementById('getCaptchaBtn').addEventListener('click', function() {
        const email = document.getElementById('register-email').value.trim();

        // 验证邮箱格式
        if (!email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
            showValidationError('register-email', '请输入有效的邮箱地址');
            return;
        }

        // 禁用按钮防止重复点击
        this.disabled = true;
        this.textContent = '发送中...';

        // 发送请求获取验证码
        fetch('/send_captcha_to_email', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ user_mail: email })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('验证码已发送到您的邮箱');
                // 开始60秒倒计时
                startCountdown(60);
            } else {
                alert(data.message || '发送验证码失败');
                this.disabled = false;
                this.textContent = '获取验证码';
            }
        })
        .catch(error => {
            console.error('发送验证码失败:', error);
            alert('发送验证码失败，请重试');
            this.disabled = false;
            this.textContent = '获取验证码';
        });
    });

    // 倒计时函数
    function startCountdown(seconds) {
        const btn = document.getElementById('getCaptchaBtn');
        let remaining = seconds;

        const timer = setInterval(() => {
            btn.textContent = `${remaining}秒后重试`;
            remaining--;

            if (remaining < 0) {
                clearInterval(timer);
                btn.disabled = false;
                btn.textContent = '获取验证码';
            }
        }, 1000);
    }
});

//        // 检查用户名是否已被注册
//        if (userManager.userExists(email)) {
//            showValidationError('register-email', '该邮箱已被注册');
//            return;
//        }

//        // 添加加载状态
//        const submitBtn = document.querySelector('.login-button');
//        submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 注册中';
//        submitBtn.disabled = true;

//        try {
//            // 模拟API请求延迟
//            await new Promise(resolve => setTimeout(resolve, 1500));
//
//            // 创建新用户对象并添加到数组
//            userManager.saveUser({
//                username: username, // 使用正确的用户名
//                email: email,       // 添加邮箱字段
//                password: password
//            });
//
//            // 注册成功提示并跳转
//            alert('注册成功！即将跳转到登录页面...');
//            setTimeout(() => {
//                window.location.href = '/login';
//            }, 1500);
//        } catch (error) {
//            // 错误处理
//            alert('注册失败：' + error.message);
//            submitBtn.innerHTML = '注册';
//            submitBtn.disabled = false;
//        }
//    });
//
//    // 返回登录处理
//    document.querySelector('.return-login').addEventListener('click', (e) => {
//        e.preventDefault();
//        window.location.href = '/login';
//    });

//    // 添加实时验证
//    document.getElementById('user_name').addEventListener('blur', validateUsernameInput); // 新增用户名验证
//    document.getElementById('register-email').addEventListener('blur', validateEmailInput);
//    document.getElementById('register-password').addEventListener('blur', validatePasswordInput);
//    document.getElementById('confirm-password').addEventListener('blur', validateConfirmPassword);


// 新增用户名验证
function validateUsernameInput() {
    const username = this.value.trim();
    if (!username) {
        showValidationError('user_name', '请输入用户名');
    } else {
        showValidationSuccess('user_name');
    }
}

// 验证邮箱输入
function validateEmailInput() {
    const email = this.value.trim();
    if (!email) return;

    if (!validateEmail(email)) {
        showValidationError('register-email', '请输入有效的邮箱地址');
    } else {
        showValidationSuccess('register-email');
    }
}

// 验证密码输入
function validatePasswordInput() {
    const password = this.value;
    if (!password) return;

    const error = validatePassword(password);
    if (error) {
        showValidationError('register-password', error);
    } else {
        showValidationSuccess('register-password');
    }
}

// 验证确认密码
function validateConfirmPassword() {
    const password = document.getElementById('register-password').value;
    const confirmPassword = this.value;

    if (password && confirmPassword && password !== confirmPassword) {
        showValidationError('confirm-password', '两次输入的密码不一致');
    } else if (confirmPassword) {
        showValidationSuccess('confirm-password');
    }
}

// 验证邮箱格式
function validateEmail(email) {
    const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return re.test(email);
}

// 验证密码格式
function validatePassword(password) {
    if (password.length < 8) {
        return '密码长度至少为8位';
    }

    if (!/[a-zA-Z]/.test(password) || !/\d/.test(password)) {
        return '密码必须包含字母和数字';
    }

    return null;
}

// 显示验证错误
function showValidationError(inputId, message) {
    const inputGroup = document.getElementById(inputId).closest('.input-group');
    inputGroup.classList.add('error');
    inputGroup.classList.remove('success');

    let errorElement = inputGroup.querySelector('.error-message');
    if (!errorElement) {
        errorElement = document.createElement('div');
        errorElement.className = 'error-message';
        inputGroup.appendChild(errorElement);
    }

    errorElement.textContent = message;
    errorElement.style.display = 'block';
}

// 显示验证成功
function showValidationSuccess(inputId) {
    const inputGroup = document.getElementById(inputId).closest('.input-group');
    inputGroup.classList.remove('error');
    inputGroup.classList.add('success');

    const errorElement = inputGroup.querySelector('.error-message');
    if (errorElement) {
        errorElement.style.display = 'none';
    }
}

// 重置验证错误
function resetValidationErrors() {
    document.querySelectorAll('.input-group').forEach(group => {
        group.classList.remove('error', 'success');
        const errorElement = group.querySelector('.error-message');
        if (errorElement) {
            errorElement.style.display = 'none';
        }
    });
}

// 生成验证码
function generateCaptcha(ctx) {
    const canvas = ctx.canvas;
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    // 生成随机验证码
    const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
    let captcha = '';
    for (let i = 0; i < 4; i++) {
        captcha += chars.charAt(Math.floor(Math.random() * chars.length));
    }

    // 绘制验证码背景
    ctx.fillStyle = '#f9f9f9';
    ctx.fillRect(0, 0, canvas.width, canvas.height);

    // 绘制干扰线
    for (let i = 0; i < 5; i++) {
        ctx.beginPath();
        ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height);
        ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height);
        ctx.strokeStyle = `rgba(0, 0, 0, ${Math.random() * 0.3 + 0.1})`;
        ctx.lineWidth = 1;
        ctx.stroke();
    }

    // 绘制验证码文本
    for (let i = 0; i < captcha.length; i++) {
        ctx.save();
        ctx.font = `bold ${Math.floor(Math.random() * 10 + 24)}px Arial`;
        ctx.fillStyle = `rgb(${Math.floor(Math.random() * 100)}, ${Math.floor(Math.random() * 100)}, ${Math.floor(Math.random() * 100)})`;
        ctx.translate(25 * i + 10, 30);
        ctx.rotate((Math.random() - 0.5) * 0.4);
        ctx.fillText(captcha[i], 0, 0);
        ctx.restore();
    }

    return captcha;
}